﻿using System.Windows;
using System.Windows.Input;

namespace WPFTemplateLib.WpfHelpers
{
    /// <summary>
    /// 防止触摸事件提升为鼠标事件
    /// https://social.msdn.microsoft.com/Forums/vstudio/en-US/9b05e550-19c0-46a2-b19c-40f40c8bf0ec/
    /// http://dlgcy.com/wpf-touch-event-promote-to-touch-event-and-datagrid-touch-problem/
    /// </summary>
    public static class PreventTouchToMousePromotion
    {
        /// <summary>
        /// 防止触摸事件提升为鼠标事件（启用）
        /// </summary>
        /// <param name="root">根元素</param>
        public static void PreventTouchToMouse_Register(this FrameworkElement root)
        {
            root.PreviewMouseDown += Evaluate;
            root.PreviewMouseMove += Evaluate;
            root.PreviewMouseUp += Evaluate;
        }

        private static void Evaluate(object sender, MouseEventArgs e)
        {
            //StylusDevice属性，触屏操作连带触发时不为null，鼠标触发时为null;
            if (e.StylusDevice != null)
            {
                e.Handled = true; //如果判断为 由触屏引发，则将事件标记为已处理；
            }
        }

        /// <summary>
        /// 防止触摸事件提升为鼠标事件（禁用）
        /// </summary>
        /// <param name="root">根元素</param>
        public static void PreventTouchToMouse_UnRegister(this FrameworkElement root)
        {
            root.PreviewMouseDown -= Evaluate;
            root.PreviewMouseMove -= Evaluate;
            root.PreviewMouseUp -= Evaluate;
        }
    }
}
